import os
import json
from typing import Dict, Any
from huggingface_hub import InferenceClient

class TextSummarizer:
    """文本摘要器，使用Hugging Face的mT5多语言模型"""
    
    def __init__(self):
        """初始化文本摘要器"""
        self.client = None
        self._initialize_client()
    
    def _initialize_client(self):
        """初始化Hugging Face客户端"""
        try:
            api_key = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
            if not api_key:
                # 尝试从配置文件读取
                config_path = os.path.join(os.path.dirname(__file__), '..', 'config.json')
                if os.path.exists(config_path):
                    with open(config_path, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        api_key = config.get("HUGGINGFACEHUB_API_TOKEN")
            
            if api_key:
                self.client = InferenceClient(
                    provider="hf-inference",
                    api_key=api_key,
                )
            else:
                print("警告: 未找到Hugging Face API密钥")
        except Exception as e:
            print(f"初始化Hugging Face客户端失败: {str(e)}")
    
    def summarize_text(self, text: str, min_length: int = 30) -> Dict[str, Any]:
        """
        对文本进行摘要
        Args:
            text: 需要摘要的文本
            min_length: 摘要的最小长度
            
        Returns:
            包含摘要结果的字典
        """
        if not self.client:
            return {
                "success": False,
                "error": "Hugging Face客户端未初始化，请检查API密钥配置"
            }
        
        if not text or not text.strip():
            return {
                "success": False,
                "error": "输入文本不能为空"
            }
        
        try:
            # 调用Hugging Face API进行摘要
            result = self.client.summarization(
                text,
                model="csebuetnlp/mT5_multilingual_XLSum",
                generate_parameters={"min_length": min_length}
            )
            
            return {
                "success": True,
                "summary": result.summary_text,
                "original_length": len(text),
                "summary_length": len(result.summary_text),
                "model": "csebuetnlp/mT5_multilingual_XLSum"
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"摘要生成失败: {str(e)}"
            }
    
    def batch_summarize(self, texts: list, max_length: int = 150, min_length: int = 30) -> Dict[str, Any]:
        if not isinstance(texts, list):
            return {
                "success": False,
                "error": "输入必须是文本列表"
            }
        
        results = []
        for i, text in enumerate(texts):
            if isinstance(text, str):
                result = self.summarize_text(text, max_length, min_length)
                result["index"] = i
                results.append(result)
            else:
                results.append({
                    "success": False,
                    "error": f"第{i}项不是有效的文本",
                    "index": i
                })
        
        return {
            "success": True,
            "results": results,
            "total": len(texts),
            "successful": sum(1 for r in results if r.get("success", False))
        }

# 创建全局实例
text_summarizer = TextSummarizer()